"""
日志系统模块
提供结构化的日志记录功能
"""
import logging
import os
from datetime import datetime
from typing import Optional


class LogManager:
    """日志管理器类"""
    
    def __init__(self, log_dir: str = "logs", log_level: int = logging.INFO):
        self.log_dir = log_dir
        self.log_level = log_level
        self._setup_logging()
    
    def _setup_logging(self):
        """设置日志配置"""
        # 创建日志目录
        if not os.path.exists(self.log_dir):
            os.makedirs(self.log_dir)
        
        # 配置日志格式
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        
        # 创建文件处理器
        log_file = os.path.join(self.log_dir, f"videograbber_{datetime.now().strftime('%Y%m%d')}.log")
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setLevel(self.log_level)
        file_handler.setFormatter(formatter)
        
        # 创建控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.WARNING)
        console_handler.setFormatter(formatter)
        
        # 配置根日志器
        root_logger = logging.getLogger()
        root_logger.setLevel(self.log_level)
        root_logger.addHandler(file_handler)
        root_logger.addHandler(console_handler)
        
        # 创建应用日志器
        self.app_logger = logging.getLogger('VideoGrabber')
        self.download_logger = logging.getLogger('VideoGrabber.Download')
        self.ui_logger = logging.getLogger('VideoGrabber.UI')
    
    def get_logger(self, name: str) -> logging.Logger:
        """获取指定名称的日志器"""
        return logging.getLogger(f'VideoGrabber.{name}')
    
    def log_download_start(self, url: str, filename: str, save_path: str):
        """记录下载开始"""
        self.download_logger.info(f"开始下载: URL={url}, 文件名={filename}, 保存路径={save_path}")
    
    def log_download_progress(self, url: str, progress: int, downloaded: int, total: int):
        """记录下载进度"""
        self.download_logger.debug(f"下载进度: URL={url}, 进度={progress}%, 已下载={downloaded}, 总大小={total}")
    
    def log_download_complete(self, url: str, filename: str, save_path: str, file_size: int):
        """记录下载完成"""
        self.download_logger.info(f"下载完成: URL={url}, 文件名={filename}, 保存路径={save_path}, 文件大小={file_size}")
    
    def log_download_error(self, url: str, error: str):
        """记录下载错误"""
        self.download_logger.error(f"下载失败: URL={url}, 错误={error}")
    
    def log_download_cancelled(self, url: str):
        """记录下载取消"""
        self.download_logger.warning(f"下载已取消: URL={url}")
    
    def log_ui_action(self, action: str, details: Optional[str] = None):
        """记录UI操作"""
        msg = f"UI操作: {action}"
        if details:
            msg += f" - {details}"
        self.ui_logger.info(msg)
    
    def log_error(self, component: str, error: str, exception: Optional[Exception] = None):
        """记录错误"""
        logger = self.get_logger(component)
        if exception:
            logger.error(f"错误: {error}", exc_info=True)
        else:
            logger.error(f"错误: {error}")
    
    def cleanup_old_logs(self, days: int = 30):
        """清理旧日志文件"""
        try:
            current_time = datetime.now()
            for filename in os.listdir(self.log_dir):
                if filename.endswith('.log'):
                    file_path = os.path.join(self.log_dir, filename)
                    file_time = datetime.fromtimestamp(os.path.getctime(file_path))
                    if (current_time - file_time).days > days:
                        os.remove(file_path)
                        self.app_logger.info(f"已删除旧日志文件: {filename}")
        except Exception as e:
            self.app_logger.error(f"清理日志文件失败: {e}")


# 全局日志管理器实例
log_manager = LogManager()